﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using ComicIsland.App.Controls;
using ComicIsland.App.Resources;
using ComicIsland.Common;
using ComicIsland.Common.Entities;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.Entities.LocalJson;
using ComicIsland.Common.StorageHelper;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Info;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using WeiboSdk;
using WeiboSdk.PageViews;

namespace ComicIsland.App.Views
{
    public partial class PersonalCenterPage : PhoneApplicationPage
    {
        public PersonalCenterPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            //if (NavigationService.BackStack.Any())
            //{
            //    var item = NavigationService.BackStack.Where(p => p.Source.ToString().EndsWith("QQAuthenticationPage.xaml")).FirstOrDefault<JournalEntry>();
            //    if (item == null)
            //    {
            //        NavigationService.RemoveBackEntry();
            //    }
            //}
            if (this.NavigationService.BackStack.Any() && this.NavigationService.BackStack.Count() > 1)
            {
                for (int i = 0; i < this.NavigationService.BackStack.Count(); i++)
                {
                    var item = this.NavigationService.BackStack.ElementAt<JournalEntry>(i);
                    if (item != null)
                    {
                        if (item.Source.ToString().EndsWith("QQAuthenticationPage.xaml"))
                        {
                            this.NavigationService.RemoveBackEntry();
                        }
                    }
                }
            }

            LoadUserInfo(Helper.UserLoginType.Login);
            base.OnNavigatedTo(e);
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (this.NavigationService.BackStack.Any() && this.NavigationService.BackStack.Count() > 1)
            {
                for (int i = 0; i < this.NavigationService.BackStack.Count(); i++)
                {
                    var item = this.NavigationService.BackStack.ElementAt<JournalEntry>(i);
                    if (item != null)
                    {
                        if (item.Source.ToString().EndsWith("PersonalCenterPage.xaml"))
                        {
                            this.NavigationService.RemoveBackEntry();
                        }
                    }
                }
            }
            base.OnBackKeyPress(e);
        }

        void LoadUserInfo(Helper.UserLoginType userLoginType)
        {
            this.psbStatus.CloseStatusBar();
            if (!IsolatedStorageHelper.Instance.FileExists(KEYS.KEY_UserThirdLoginInfo))
                return;

            string localCacheData = IsolatedStorageHelper.Instance.ReadText(KEYS.KEY_UserThirdLoginInfo);
            if (string.IsNullOrWhiteSpace(localCacheData))
                return;
            var userInfo = JSONHelper.Deserialize<UserThirdLoginInfo>(localCacheData);
            if (userInfo == null)
            {
                return;
            }
            if (userInfo.ComicUserId <= 0)
            {
                this.gridUserLogin.Visibility = System.Windows.Visibility.Visible;
                this.gridUserInfo.Visibility = System.Windows.Visibility.Collapsed;
                return;
            }

            if ((int)Helper.ThirdPlatform.SinaWeibo == userInfo.ThirdPlatform || (int)Helper.ThirdPlatform.QQ == userInfo.ThirdPlatform)
            {
                DateTime expriesIn = DateTime.Parse(userInfo.InsertDateTime).AddSeconds(int.Parse(userInfo.ExpriesIn));
                if (DateTime.Compare(DateTime.Now, expriesIn) > 0)
                {
                    //已过期，需要重新登录
                    return;
                }

                this.psbStatus.OpenStatusBar(AppResources.DataLoading);
                #region 绑定数据并登录
                //{"uid":"1872997893","platform":"2","islogout":"0","gender":"1","logininfo":"","screen_name":"国学经典食疗养生楚才书店","lastloginsystemversion":"4.2.1","lastlogindevicename":"GFIVE","profile_image_url":"http:\%2F\%2Ftp2.sinaimg.cn\%2F1872997893\%2F180\%2F40019484811\%2F1","access_token":"2.008_ukCC0eYD6W06e1013bbbZfgajD"}
                string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/userlogin");//, "?", KEYS.REQUEST_QUERY_PLATFORM);
                LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());
                Dictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.Add("uid", userInfo.UserId);
                parameters.Add("platform", userInfo.ThirdPlatform.ToString());
                parameters.Add("islogout", ((int)userLoginType).ToString());
                parameters.Add("gender", userInfo.Gender);
                parameters.Add("screen_name", Helper.UriEscapeDataString(userInfo.ScreenName));
                parameters.Add("profile_image_url", userInfo.ProfileImageUrl);
                parameters.Add("access_token", userInfo.AccessToken);
                parameters.Add("lastlogindevicename", Helper.UriEscapeDataString(DeviceStatus.DeviceName));
                parameters.Add("lastloginsystemversion", Variables.GetVersion());
                //parameters.Add("logininfo", Helper.UriEscapeDataString(userInfo.DetailInfo));
                parameters.Add("logininfo", "");

                PostClientHelper proxy = new PostClientHelper(parameters);
                LogHelper.LogInfo(proxy.PostData.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                proxy.DownloadStringCompleted += (sender, e) =>
                {
                    try
                    {
                        if (e.Error != null)
                        {
                            LogHelper.LogError(e.Error.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                            return;
                        }

                        #region 获取结果处理
                        string result = e.Result;

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }

                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicUserLogin>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            var item = rootCharacterString.Info;
                            this.Dispatcher.BeginInvoke(() =>
                            {
                                if (item != null)
                                {
                                    if (userLoginType == Helper.UserLoginType.Login)
                                    {
                                        this.gridUserLogin.Visibility = System.Windows.Visibility.Collapsed;
                                        this.gridUserInfo.Visibility = System.Windows.Visibility.Visible;
                                        userInfo.ComicUserId = item.Id;
                                        this.gridUserInfo.DataContext = userInfo;
                                        this.txtUserInfo.Text = string.Format("我的话题 ({0})", item.Discusscount);
                                    }
                                    else
                                    {
                                        userInfo.ComicUserId = 0;
                                        this.gridUserLogin.Visibility = System.Windows.Visibility.Visible;
                                        this.gridUserInfo.Visibility = System.Windows.Visibility.Collapsed;
                                    }
                                    string json = JSONHelper.Serialize<UserThirdLoginInfo>(userInfo);
                                    IsolatedStorageHelper.Instance.WriteText(json, KEYS.KEY_UserThirdLoginInfo, true);
                                }
                            });
                        }
                        #endregion 获取结果处理
                    }
                    catch (Exception err)
                    {
                    }
                    finally
                    {
                        this.Dispatcher.BeginInvoke(() =>
                        {
                            this.psbStatus.CloseStatusBar();
                        });
                    }
                };
                proxy.DownloadStringAsync(new Uri(requestUrl, UriKind.Absolute));
                #endregion 绑定数据并登录
            }
            else
            {
                //不处理
            }



        }





        /// <summary>
        /// 软件设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAppConfig_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NaviService.Navigate(ComicIslandPage.PersonalCenterAppConfigPage);
        }

        /// <summary>
        /// 用户注销
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void appBarSignOut_Click(object sender, EventArgs e)
        {
            this.LoadUserInfo(Helper.UserLoginType.Logout);
        }

        /// <summary>
        /// 下载管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAppConfigDownloadManage_Click(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NaviService.Navigate(ComicIslandPage.DCVDownloadComicList);
        }

        /// <summary>
        /// 进入话题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridUserInfo_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {

            var userLoginInfo = this.gridUserInfo.DataContext as UserThirdLoginInfo;
            if (userLoginInfo != null)
            {
                string param = string.Concat("?userId=", userLoginInfo.ComicUserId);
                NaviService.Navigate(ComicIslandPage.CommunityReviewUserPage, param);
            }
        }

        /// <summary>
        /// 意见反馈
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFeedback_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NaviService.Navigate(ComicIslandPage.OtherComicFeedbackPage);
        }

        /// <summary>
        /// 评价评分
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMarketReview_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            try
            {
                MarketplaceReviewTask mdr = new MarketplaceReviewTask();
                mdr.Show();
            }
            catch
            {
                MessageToastManager.Show("未找到评价入口，您可以在应用列表中长按后进行此操作！");
            }
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridUserLogin_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.oauthControl.OnClose += oauthControl_OnClose;
            this.popupLogin.IsOpen = true;
        }

        void oauthControl_OnClose(object sender, EventArgs e)
        {
            this.popupLogin.IsOpen = false;
        }

        /// <summary>
        /// 软件分享
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAppShared_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            ShareData shareData = new ShareData();
            shareData.Content = "报告大王！，发现漫画神器-漫画岛，满满全是真(bi)爱(ge)！下载地址：http://www.manhuadao.cn";
            shareData.ImageSavedType = (int)ImageLocationType.AppFile;
            shareData.ImageUrl = "/Images/tmp/screen1.jpg";
            this.sharedControl.shareData = shareData;
            this.sharedControl.OnClose += delegate(object s1, EventArgs e1)
            {
                this.popupShared.IsOpen = false;
            };
            this.popupShared.IsOpen = true;
        }

        #region 使用帮助
        AppHelpControl appHelpControl = new AppHelpControl();
        private void btnUseHelp_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.ApplicationBar.IsVisible = false;
            appHelpControl.SetPhoneApplicationPage(this, ComicIslandPage.PersonalCenterPage);
            Grid.SetRow(this.appHelpControl, 0);
            Grid.SetRowSpan(this.appHelpControl, 4);
            this.LayoutRoot.Children.Add(this.appHelpControl);
        }

        public void RemoveHelp()
        {
            if (this.LayoutRoot.Children.IndexOf(this.appHelpControl) >= 0)
            {
                this.LayoutRoot.Children.Remove(this.appHelpControl);
            }            
        }
        #endregion 使用帮助


    }
}





